<template>
  <el-form :rules="rules" :model="form" class="form" ref="loginForm">
    <el-form-item >
    </el-form-item>
    <el-form-item prop="username">
      <el-input ref="username" v-model="form.username"  class="el-input-my" placeholder="用户名或邮箱">
        <template #prefix>
          <i class="iconfont icon-yonghuming"></i>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input @keydown.enter.native="loginAccount('loginForm')" ref="password" :type="showPass" placeholder="密码" type="password" v-model="form.password" class="el-input-my" >
        <template #prefix>
          <i class="iconfont icon-mima"></i>
        </template>
        <template #suffix>
          <i :class="passwordIcon" @click="showPassword"></i>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item>
      <el-button :loading="loading" type="primary" class="login-button" @click="loginAccount('loginForm')">
        <i class="iconfont icon-denglu"></i>&nbsp;
        登录
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import md5 from "js-md5";

export default {
  name: "loginForm",
  props:['queryPath'],
  data(){
    return{
      loading:false,
      form:{
        username:'',
        password:''
      },
      showPass:'password',
      passwordIcon:'iconfont icon-yanjing_yincang poi',
      rules:{
        username: [{required:true,message:'输入不能为空',trigger:['blur','change']}],
        password: [{required:true,message:'输入不能为空',trigger:['blur','change']}]
      }
    }
  },
  mounted() {
    if (this.form.username === '') {
      this.$refs.username.focus()
    } else if (this.form.password === '') {
      this.$refs.password.focus()
    }
  },
  methods:{
    showPassword(){
      if(this.showPass==='password'){
        this.showPass='text'
        this.passwordIcon='iconfont icon-yanjing_xianshi poi'
      }
      else{
        this.showPass='password'
        this.passwordIcon='iconfont icon-yanjing_yincang'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    loginAccount(formName){
      this.loading=true
      this.$refs[formName].validate((valid)=>{
        if (valid){
          const password=md5(this.form.password)
          const form={username:this.form.username.trim(),password}
          this.$store.dispatch("user/handleLogin",form).then((value)=>{
            this.loading=false
            if (this.$websocket.ws&&this.$websocket.ws.readyState===1){
              this.$websocket.ws.close()
            }
            this.$router.replace({path:this.queryPath ||'/homepage'})
          }).catch(()=>{
            this.loading=false
          })
         /* login(this.form.username, password).then(res=>{
            console.log(res)
          })*/
        }else{
          this.loading=false
          return false
        }
      })

    }
  }
}
</script>

<style scoped>
.poi{
  cursor: pointer;
}
</style>
